package com.rk.topN;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;
import java.util.Iterator;
import java.util.TreeMap;

public class TopNMapper extends Mapper<LongWritable, Text, ViewCountBean, Text> {

    // 定义一个TreeMap作为存储数据的容器，天然按key排序
    private TreeMap<ViewCountBean, Text> map = new TreeMap<ViewCountBean, Text>();

    private ViewCountBean bean;


    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

        String line = value.toString();
        if(line == null || !line.contains("\t")){
            return;
        }

        Text v = new Text();
        bean = new ViewCountBean();
        String[] words = line.split("\t");
        String docId = words[0];
        String viewTotalCount = words[1];

        bean.setDocId(Long.parseLong(docId));
        bean.setViewTotalCount(Long.parseLong(viewTotalCount));

        v.set(docId);
        map.put(bean, v);

        // 限制TreeMap的数据量，超过10条九删除掉总浏览量最小的数据
        if(map.size() > 10){
            map.remove(map.lastKey());
        }
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        Iterator<ViewCountBean> beans = map.keySet().iterator();
        while (beans.hasNext()){
            ViewCountBean bean = beans.next();
            context.write(bean, map.get(bean));
        }
    }
}
